/**
 * <p>Title: ServiceZMCME1.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 余虎
 * @version 1.0
 * <pre>Histroy:
 *          2011-7-7 上午11:09:24  余虎  Create
 *</pre>
 */
package com.baosight.sczx.zm.cm.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiColumn;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.soa.SoaManager;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.zm.Utils;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.cm.MaterialBase;
import com.baosight.sczx.common.zm.cInterface.cs.InitialData;
import com.baosight.sczx.common.zm.cInterface.cs.SystemSettingCM;
import com.baosight.sczx.zm.cm.domain.ZMCMDepot;
import com.baosight.sczx.zm.cm.domain.ZMCMExportApplicationDetail;
import com.baosight.sczx.zm.cm.domain.ZMCMMaterialBase;
import com.baosight.sczx.zm.cm.domain.ZMCMTurnoverRecord;

/**出库
 * <p>Title: ServiceZMCME1.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 余虎
 * @version 1.0
 * <pre>Histroy:
 *          2011-7-7 上午11:09:24  余虎  Create
 *</pre>
 */
public class ServiceZMCME1 extends ServiceEPBase {

	/**初始化数据
	 * <p>Function: initLoad</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCME1</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-7上午11:09:55 余虎
	 * </p>
	 *
	*/
	@Override
	public EiInfo initLoad(EiInfo inInfo) {
		inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的
		EiInfo outInfo = this.query(inInfo);
		
		return outInfo;
	}

	/**查询单据信息
	 * <p>Function: query</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCME1</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-7上午11:09:55 余虎
	 * </p>
	 *
	*/
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public EiInfo query(EiInfo inInfo) 
	{
		String tmp_typeCode = "";
		String t8_typeCode = "";
    	Map inMap = new HashMap();
		String sqlmap = "ZMCMTypeManageMentSet.queryManageAllType";
		String isUseTypeManagement = SystemSettingCM.getInstance().getIsuseTypemanagement();
		if(isUseTypeManagement.equals("1"))
		{
			inMap.put("fdExportPeopleId", UserSession.getUserId());
			List _list = dao.query(sqlmap, inMap);
			List queryList = Utils.generateValidateData(_list);
			tmp_typeCode = "(tmp.fd_material_code like ''";
			t8_typeCode = "(t8.fd_material_code like ''";
			for(int j=0; j<queryList.size(); j++)
			{
				tmp_typeCode += " OR tmp.fd_material_code like '" + queryList.get(j).toString() + "%'";
				t8_typeCode += " OR t8.fd_material_code like '" + queryList.get(j).toString() + "%'";
			}
			tmp_typeCode += ")";
			t8_typeCode += ")";			
		}
		else
		{
			sqlmap = "ZMCMMaterialType.type";
			List queryList = dao.query(sqlmap, inMap);
			
			tmp_typeCode = "(tmp.fd_material_code like ''";
			t8_typeCode = "(t8.fd_material_code like ''";
			for(int i=0; i<queryList.size(); i++)
			{
				Map _map = (Map)queryList.get(i);
				tmp_typeCode += " OR tmp.fd_material_code like '" + _map.get("fdTypeCode").toString() + "%'";
				t8_typeCode += " OR t8.fd_material_code like '" + _map.get("fdTypeCode").toString() + "%'";
			}
			tmp_typeCode += ")";
			t8_typeCode += ")";			
		}
		
		if(inInfo.getBlock(EiConstant.queryBlock) == null)
		{
			inInfo.addBlock(EiConstant.queryBlock);
		}
		inInfo.getBlock(EiConstant.queryBlock).setCell(0, "fdMaterialCodeStr_tmp", tmp_typeCode);
		inInfo.getBlock(EiConstant.queryBlock).setCell(0, "fdMaterialCodeStr_t8", t8_typeCode);
		
		EiInfo outInfo = new EiInfo();
		outInfo.addBlock(Utils.generateOutBlock(EiConstant.resultBlock, new ZMCMExportApplicationDetail(), inInfo, "ZMCMExportApplicationDetail.queryForDetail", false));	
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cs.units"));
		outInfo.addBlock(generateBusinessType());
		outInfo.addBlock(generateMaterialType());
		return outInfo;
	}
	
	/**新增出库
	 * <p>Function: insert</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCME1</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-7上午11:09:55 余虎
	 * </p>
	 *
	*/
	@Override
	public EiInfo insert(EiInfo inInfo) {
		
		EiInfo outInfo;
		boolean validateValue = validate(inInfo, "ZMCMExportMaterial.validateNoteCode", new HashMap<String, String>());

		if(validateValue)//判断编号是否重复
		{
			return inInfo;
		}
		else
		{
			if(!validateBaseNum(inInfo))
			{
				return inInfo;
			}
			
			EiInfo resultInfo = new EiInfo();
			String fdResourceNoteCode = inInfo.getBlock(EiConstant.queryBlock).getCellStr(0, "fdResourceNoteCode");
			resultInfo.addBlock(inInfo.getBlock(EiConstant.resultBlock));
			resultInfo.addBlock(inInfo.getBlock(EiConstant.queryBlock));
			
			//新增出库--主表记录-ZMCMExportMaterial
			String ZMCMExportMaterialKeyId = TablePk.getInstance().getNextValue("T_CM_EXPORTMATERIAL");
			inInfo.getBlock("inqu_status").setCell(0, "fdKeyId", ZMCMExportMaterialKeyId);//主表主键
			inInfo.getBlock("inqu_status").setCell(0, "fdYear", MaterialBase.getAccountDate(inInfo.getBlock("inqu_status").getCellStr(0, "fdNoteDate"))[0]);
			inInfo.getBlock("inqu_status").setCell(0, "fdMonth", MaterialBase.getAccountDate(inInfo.getBlock("inqu_status").getCellStr(0, "fdNoteDate"))[1]);
			inInfo.getBlock("inqu_status").setCell(0, "fdResourceNoteCode", "");
			outInfo = super.insert(inInfo, "ZMCMExportMaterial.insert", "inqu_status");
			
			//新增出库--明细记录-ZMCMExportmaterialDetail
			String fdApplyDepartmentId = UserSession.getInSessionProperty("orgCode").toString();//使用单位ID
			for(int i=0; i<inInfo.getBlock("result").getRowCount(); i++)
			{	
				String detailId = TablePk.getInstance().getNextValue("T_CM_EXPORTMATERIAL_DETAIL");
				String fdApplicationDetailKeyId = inInfo.getBlock("result").getCellStr(i, "fdKeyId");
				inInfo.getBlock("result").setCell(i, "initKeyId", fdApplicationDetailKeyId);
				inInfo.getBlock("result").setCell(i, "fdMaterialName", inInfo.getBlock("result").getCell(i, "fdMaterial"));
				inInfo.getBlock("result").setCell(i, "fdExportmaterialId", ZMCMExportMaterialKeyId);
				inInfo.getBlock("result").setCell(i, "fdKeyId", detailId);//从表主键
				inInfo.getBlock("result").setCell(i, "fdApplyDepartmentId", fdApplyDepartmentId);
				inInfo.getBlock("result").setCell(i, "fdDetailId", detailId);//保存从表主键
			}
			outInfo = super.insert(inInfo, "ZMCMExportmaterialDetail.insert", "result");
			
			EiInfo result = insert_2LEVELBASEACCOUNT(resultInfo,fdResourceNoteCode);//在二级库存台账列表中新增一条入库信息
			if(result.getStatus() == -1)
			{
				outInfo.setStatus(-1);
				outInfo.setMsg(result.getMsg());
				return outInfo;
			}
			
			result = update_ZMCMMaterialBase(resultInfo);//更新库房信息
			if(result.getStatus() == -1)
			{
				outInfo.setStatus(-1);
				outInfo.setMsg(result.getMsg());
				return outInfo;
			}
			
			insert_EXPORT_APPLICATION(resultInfo);//更新回收,申请从表状态,领料申请主表状态
			updateMaterialRation(resultInfo);//更新费用额度领用额度
			
			String NoteCode = queryfdCode();
			outInfo.set("fdNoteCode", NoteCode);//生成新的编号
		}
		return outInfo;
	}

	/**
	 * <p>查询code</p>
	 * <p>Function: queryfdCode</p>
	 * <p>Description: </p>
	 * <p>return value:String</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-18下午03:56:11 余虎
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String queryfdCode()
	{
		List<Map> _list = new ArrayList<Map>();
		HashMap	params = new HashMap<String, String>();
		String startStr = "CK" + StaticTools.getDateDefault() + StaticTools.getTime().replaceAll(":", "");
		String defaultStr = startStr + "001";//定义格式
		_list = dao.query("ZMCMExportMaterial.queryLatestNoteCode", params);
		if(_list!=null && _list.size() > 0) {
			String str = _list.get(0).get("fdNoteCode").toString();
			defaultStr = convertStr(startStr, str);
		}
		return defaultStr;
	}
	
	/**
	 * <p>构造编号</p>
	 * <p>Function: convertStr</p>
	 * <p>Description: </p>
	 * <p>return value:String</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-7上午10:52:36 余虎
	 * </p>
	 *
	 */
	private String convertStr(String startStr, String str)
	{
		String str1 = str.substring(16,19);//第二部分的流水号
		int nub = Integer.parseInt(str1); 
		str1 = Integer.toString(nub+1);
		if(str1.length() == 1){
			return startStr+"00"+str1;
		}else if (str1.length() == 2)
		{
			return startStr+"0"+str1;
		}else
		{
			return startStr+str1;
		}
	}
	
	/**
	 * <p>删除方法</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCME1</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-7上午11:09:55 余虎
	 * </p>
	 *
	*/
	@Override
	public EiInfo delete(EiInfo inInfo) {

		return super.delete(inInfo);
	}
	
	/**
	 * <p>更新方法</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCME1</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-7上午11:09:55 余虎
	 * </p>
	 *
	*/
	@Override
	public EiInfo update(EiInfo inInfo) {
		return super.update(inInfo);
	}

	/**
	 * <p>当材料基础设置为使用二级库存的时候，在二级库存台账列表中新增一条入库信息T_CM_2LEVELBASEACCOUNT</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCME1</p>
	 * <p>History:
	 *    2011-7-21下午08:08:04 张坤
	 * </p>
	 *
	*/
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private EiInfo insert_2LEVELBASEACCOUNT(EiInfo inInfo,String resourceNoteCode)
	{
		Map inMap = new HashMap();
		inMap.put("fdApplicationCode", resourceNoteCode);
		String fdDepotCode = "";
		String fdDepotName = "";
		
		List _list = dao.query("ZMCMExportMaterial.queryDepotWithApplication", inMap);
		
		if(_list.size() > 0)
		{
			Map _map = (Map)_list.get(0);
			fdDepotCode = _map.get("fdDepotCode").toString();
			fdDepotName = _map.get("fdDepotName").toString();
		}
		
		if(!fdDepotCode.equals("") && !fdDepotName.equals(""))
		{
			for(int i=0; i<inInfo.getBlock("result").getRowCount(); i++)           
			{
				String fdMaterialId = inInfo.getBlock("result").getCellStr(i, "fdMaterialId");
				Map _map = new HashMap();
				_map.put("fdMaterialId", fdMaterialId);
				
				List mb_list = dao.query("ZMCMMaterialBase.query", _map);
	
				if(mb_list.size() <= 0)
				{
					inInfo.setStatus(-1);
					String fdMaterialName = inInfo.getBlock("result").getCellStr(i, "fdMaterialName");
					String fdMaterialCode = inInfo.getBlock("result").getCellStr(i, "fdMaterialCode");
					inInfo.setMsg("库存中没有物资" + "[" + fdMaterialCode + "]" + fdMaterialName + "，暂时无法办理出库。");
					
					return inInfo;
				}
				ZMCMMaterialBase mb = (ZMCMMaterialBase)mb_list.get(0);
				double cfdPrice = mb.getFdPrice();//计划单价
				double cfdActualPrice = mb.getFdActualPrice();//实际单价
				
				String  fdKeyId = TablePk.getInstance().getNextValue("T_CM_2LEVELBASEACCOUNT");
				inInfo.getBlock("result").setCell(i, "initKeyId", inInfo.getBlock("result").getCellStr(i, "initKeyId"));//记录领料申请从表主键
				inInfo.getBlock("result").setCell(i, "fdExportNoteId", inInfo.getBlock("inqu_status").getCellStr(0, "fdKeyId"));
				inInfo.getBlock("result").setCell(i, "fdKeyId", fdKeyId);
				inInfo.getBlock("result").setCell(i, "fdType", "入库");
				inInfo.getBlock("result").setCell(i, "fdRecordStatus", "正常");
				inInfo.getBlock("result").setCell(i, "fdInvoiceType", inInfo.getBlock("result").getCellStr(i, "fdMaterialType"));
				inInfo.getBlock("result").setCell(i, "fdMaterialType", "无");
				inInfo.getBlock("result").setCell(i, "fdDepotCode", fdDepotCode);
				inInfo.getBlock("result").setCell(i, "fdDepotName", fdDepotName);
				inInfo.getBlock("result").setCell(i, "fdNum", Double.parseDouble(inInfo.getBlock("result").getCellStr(i, "fdActualNumber")));
				inInfo.getBlock("result").setCell(i, "fdPlanPrice", cfdPrice);
				inInfo.getBlock("result").setCell(i, "fdPrice", cfdActualPrice);
				inInfo.getBlock("result").setCell(i, "fdDate", StaticTools.getDate());
				inInfo.getBlock("result").setCell(i, "fdMaterialInnerCode",  "root" +inInfo.getBlock("result").getCellStr(i, "fdMaterialCode"));
			}
		
			EiInfo outInfo = super.insert(inInfo, "ZMCM2levelbaseaccount.insert");
			 
			if(outInfo.getStatus() == -1) 
			{
				inInfo.setStatus(-1);
				inInfo.setMsg(outInfo.getMsg());
			}
		
			for(int i=0; i<inInfo.getBlock("result").getRowCount(); i++)
			{
				String fdMaterialId = inInfo.getBlock("result").getCellStr(i, "fdMaterialId");
				Map _map = new HashMap();
				_map.put("fdMaterialId", fdMaterialId);
				_map.put("fdDepotCode", fdDepotCode);
				
				List tmp = dao.query("ZMCM2levelmaterialbase.validateexist", _map);
				if(tmp.size() > 0)
				{
					Map tmp1 = (Map)tmp.get(0);
					double fdNum = Double.parseDouble(tmp1.get("fdNum").toString());
					//double fdPlanPrice = Double.parseDouble(tmp1.get("fdPlanPrice").toString());
					double fdPrice = Double.parseDouble(tmp1.get("fdPrice").toString());
					double actualNum = Double.parseDouble(inInfo.getBlock("result").getCellStr(i, "fdNum"));
					double cfdPrice = Double.parseDouble(inInfo.getBlock("result").getCellStr(i, "fdPrice"));
					
					_map.put("fdNum", BigDecimal.valueOf((fdNum+actualNum))+"");
					_map.put("fdPlanPrice", inInfo.getBlock("result").getCell(i, "fdPlanPrice"));
					_map.put("fdPrice", BigDecimal.valueOf(((fdNum*fdPrice)+(actualNum*cfdPrice))/(fdNum+actualNum))+"");
					
					dao.update("ZMCM2levelmaterialbase.updateInvalid1", _map);
				}
				else
				{
					Map tmp1 = inInfo.getBlock("result").getRow(i);
					tmp1.put("fdKeyId", TablePk.getInstance().getNextValue("T_CM_2LEVELMATERIALBASE"));
					dao.insert("ZMCM2levelmaterialbase.insert", tmp1);
				}
			}
		}
		return inInfo;
	}
	
	/**
	 * <p>新增回收状态----- T_CM_TURNOVERRECORD</p>
	 * <p>更新领料申请--从表状态--T_CM_EXPORT_APPLICATION_DETAIL</p>
	 * <p>更新领料申请--主表状态--T_CM_EXPORT_APPLICATION</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCME1</p>
	 * <p>History:
	 *    2011-7-21下午08:08:04 张坤
	 * </p>
	 *
	*/
	@SuppressWarnings("rawtypes")
	private EiInfo insert_EXPORT_APPLICATION(EiInfo inInfo) 
	{
		 String fdApplicationId = "";
		 String fdkeyId = "";
		 EiInfo turnInfo = new EiInfo();
		 String fdExportmaterialDetailId = "";
		 String fdTurnoverRecordlId = "";
		 turnInfo.addBlock(EiConstant.resultBlock);
		 turnInfo.getBlock(EiConstant.resultBlock).addBlockMeta((new ZMCMTurnoverRecord()).eiMetadata);

		 for(int i=0; i<inInfo.getBlock("result").getRowCount(); i++)
		 {
			 fdApplicationId = inInfo.getBlock("result").getCellStr(i, "fdApplicationId");
			 fdExportmaterialDetailId = inInfo.getBlock("result").getCellStr(i, "fdDetailId");
			 fdkeyId = inInfo.getBlock("result").getCellStr(i, "initKeyId");
			 double fdAuditNumber = Double.valueOf(inInfo.getBlock("result").getCellStr(i, "fdAuditNumber").toString());
			 double fdExportedNumber = Double.valueOf(inInfo.getBlock("result").getCellStr(i, "fdExportedNumber").toString());

			 //当已发数量等于审批数量的时候修改领料申请明细中的状态为全部领用否则为部分领用
			 inInfo.getBlock("result").setCell(i, "fdKeyId", fdkeyId);
			 double NowfdExportedNumber = Double.parseDouble(inInfo.getBlock("result").getCellStr(i, "fdActualNumber"));
			 double fdExportedNumber2   = Double.parseDouble(inInfo.getBlock("result").getCellStr(i, "fdExportedNumber"));
			 inInfo.getBlock("result").setCell(i, "fdExportedNumber", NowfdExportedNumber);
			 fdExportedNumber = NowfdExportedNumber+fdExportedNumber2;
			 
			 //	当新增记录是判断业务类型是否为回收或周转，如果是则插入材料回收记录
			 if(!inInfo.getBlock("result").getCellStr(i, "fdBusinessType").equals("一般"))
			 {
				 Map<String, String> map = new HashMap<String, String>();
				 fdTurnoverRecordlId = TablePk.getInstance().getNextValue("T_CM_TURNOVERRECORD");
				 map.put("fdKeyId", fdTurnoverRecordlId);
				 map.put("fdMaterialId", inInfo.getBlock("result").getCellStr(i, "fdMaterialId"));
				 map.put("fdExportDate", StaticTools.getDate());
				 map.put("fdDepartment", UserSession.getInSessionProperty("orgCode").toString());
				 map.put("fdMaterialCode", inInfo.getBlock("result").getCellStr(i, "fdMaterialCode"));
				 map.put("fdMaterialName", inInfo.getBlock("result").getCellStr(i, "fdMaterialName"));
				 map.put("fdSpecModel", inInfo.getBlock("result").getCellStr(i, "fdSpecModel"));
				 map.put("fdNumber", inInfo.getBlock("result").getCellStr(i, "fdNumber"));
				 map.put("fdQuality", inInfo.getBlock("result").getCellStr(i, "fdQuality"));
				 map.put("fdMetric", inInfo.getBlock("result").getCellStr(i, "fdMetric"));
				 map.put("fdActualNumber", inInfo.getBlock("result").getCellStr(i, "fdActualNumber"));
				 map.put("fdTrunoverStatus", "发料");
				 map.put("fdRestorePlace", "无");
				 map.put("fdBusinessType", inInfo.getBlock("result").getCellStr(i, "fdBusinessType"));
				 turnInfo.getBlock(EiConstant.resultBlock).addRow(map);
				 //给出库明细表增加回收材料表主键
				 Map<String, String> _turnovermap = new HashMap<String, String>();
				 _turnovermap.put("fdKeyId", fdExportmaterialDetailId);
				 _turnovermap.put("fdTurnoverRecordlId", fdTurnoverRecordlId);
				 dao.update("ZMCMExportmaterialDetail.updateTurnoverRecordId",_turnovermap);
			 }
			 if(fdAuditNumber == fdExportedNumber)
			 {
				 inInfo.getBlock("result").setCell(i, "fdStatus", "全部领用");        		
			 }
			 else
			 {   
				 inInfo.getBlock("result").setCell(i, "fdStatus", "部分领用");
			 }
			 
		 }
		 inInfo.set(EiConstant.serviceName, "ZMCM81");	//修改领料申请--明细领料状态
		 inInfo.set(EiConstant.methodName, "updateForStatus");
		 SoaManager.invoke(inInfo);
		 
		 Map<String, String> inMap = new HashMap<String, String>();
		 inMap.put("fdApplicationId", fdApplicationId);
		 List _list = dao.query("ZMCMExportApplicationDetail.queryStrict", inMap);
		 String zbStatus = "部分";
		 for(int i=0; i<_list.size(); i++)
		 {
			 ZMCMExportApplicationDetail detail = (ZMCMExportApplicationDetail)_list.get(i);
			 if(detail.getFdStatus() == null || !"全部领用".equals(detail.getFdStatus()))
			 {
				 zbStatus = "部分";
				 break;
			 }
			 else
			 {
				 zbStatus = "全部";
				 continue;
			 }
		 }
		 
		 inInfo.set(EiConstant.serviceName, "ZMCM80");	//修改领料申请--主表领料状态
		 inInfo.set(EiConstant.methodName, "updateForStatus");
		 inInfo.set("fdKeyId", fdApplicationId);
		 inInfo.set("fdStatus", zbStatus);
		 SoaManager.invoke(inInfo);
		 
		 super.update(inInfo, "ZMCMExportApplicationDetail.updateForExportedNumber");
		 
		 if(turnInfo.getBlock(EiConstant.resultBlock).getRowCount() > 0)
		 {
			 super.insert(turnInfo, "ZMCMTurnoverRecord.insert");//新增回收表单
		 }
		 
		 
		 return inInfo;
	}
	
	/**
	 * <p>更新库房信息--------ZMCMMaterialBase</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCME1</p>
	 * <p>History:
	 *    2011-7-21下午08:08:04 张坤
	 * </p>
	 *
	*/
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private EiInfo update_ZMCMMaterialBase(EiInfo inInfo) 
	{
		EiInfo _info = new EiInfo();
		EiBlock _block = new EiBlock(EiConstant.resultBlock);
		_block.addBlockMeta((new ZMCMMaterialBase()).eiMetadata);
		_info.addBlock(new EiBlock(EiConstant.resultBlock));
		
		for(int i=0; i<inInfo.getBlock("result").getRowCount(); i++)
		{
			String fdMaterialId = inInfo.getBlock("result").getCellStr(i, "fdMaterialId");
			Map<String,String> _map = new HashMap<String,String>();
			_map.put("fdMaterialId", fdMaterialId);
			
			List _list = dao.query("ZMCMMaterialBase.query", _map);

			if(_list.size() > 0)
			{
				ZMCMMaterialBase mb = (ZMCMMaterialBase)_list.get(0);
				
				double cfdSafeNum = 0.0;
				if(mb.getFdSafeBaseNum() != null)
				{
					cfdSafeNum = mb.getFdSafeBaseNum();//安全库存数量
				}
				double cfdNum = mb.getFdNum();//库存数量
				double cfdPrice = mb.getFdPrice();//计划单价
				double cfdActualPrice = mb.getFdActualPrice();//实际单价
				double fdActualNum = Double.parseDouble(inInfo.getBlock("result").getCellStr(i, "fdActualNumber"));
				
				if(cfdSafeNum != Double.parseDouble("0"))
				{
					if((cfdNum-cfdSafeNum-fdActualNum) < Double.parseDouble("0"))
					{
						EiInfo returnInfo = new EiInfo();
						returnInfo.setStatus(-1);
						returnInfo.setMsg("物资" + inInfo.getBlock("result").getCellStr(i, "fdMaterialName") + "[" + 
								inInfo.getBlock("result").getCellStr(i, "fdMaterialCode") + 
								"]的本次要求出库量大于库存量减去安全库存量，无法办理出库！");
						
						return returnInfo;
					}
				}
				
				if((cfdNum-fdActualNum) < Double.parseDouble("0"))
				{
					EiInfo returnInfo = new EiInfo();
					returnInfo.setStatus(-1);
					returnInfo.setMsg("物资" + inInfo.getBlock("result").getCellStr(i, "fdMaterialName") + "[" + 
							inInfo.getBlock("result").getCellStr(i, "fdMaterialCode") + 
							"]的库存量小于本次要求出库量，无法办理出库！");
					
					return returnInfo;
				}
				
				Map inMap = new HashMap();
				inMap.put("fdSum", BigDecimal.valueOf((cfdNum-fdActualNum)*cfdPrice));
				inMap.put("fdNum", BigDecimal.valueOf((cfdNum-fdActualNum)));
				inMap.put("fdActualSum", BigDecimal.valueOf((cfdNum-fdActualNum)*cfdActualPrice));
				inMap.put("fdLastExportDate", StaticTools.getDate());
				inMap.put("fdMaterialId", fdMaterialId);
				if(inInfo.getBlock("result").getCellStr(i, "fdHasinvoiceNum") == null 
						||inInfo.getBlock("result").getCellStr(i, "fdHasinvoiceNum") == ""
						||inInfo.getBlock("inqu_status").getCellStr(0, "fdExportType").equals("超前出库"))
				{
					inMap.put("fdHasinvoiceNum", mb.getFdHasinvoiceNum());
				}
				else
				{
					inMap.put("fdHasinvoiceNum", inInfo.getBlock("result").getCell(i, "fdHasinvoiceNum"));
				}
				if(inInfo.getBlock("result").getCellStr(i, "fdNoinvoiceNum") == null 
						||inInfo.getBlock("result").getCellStr(i, "fdNoinvoiceNum") == ""
						||inInfo.getBlock("inqu_status").getCellStr(0, "fdExportType").equals("超前出库"))
				{
					inMap.put("fdNoinvoiceNum", mb.getFdNoinvoiceNum());
				}
				else
				{
					inMap.put("fdNoinvoiceNum", inInfo.getBlock("result").getCell(i, "fdNoinvoiceNum"));
				}
				
				dao.update("ZMCMMaterialBase.updateAfterExport", inMap);
				
				if(inInfo.getBlock("inqu_status").getCellStr(0, "fdExportType").equals("一般出库"))
				{
					if(inInfo.getBlock("result").getCell(i, "fdInvoiceType") != null)
					{
						if(inInfo.getBlock("result").getCellStr(i, "fdInvoiceType").equals("无发票"))
						{
							inMap.put("fdNoInvoiceUseNum", fdActualNum+mb.getFdNoinvoiceUseNum());
							dao.update("ZMCMMaterialBase.updateNoInvoiceUseNum", inMap);
						}
					}
					else
					{
						if(inInfo.getBlock("result").getCellStr(i, "fdMaterialType").equals("无发票"))
						{
							inMap.put("fdNoInvoiceUseNum", fdActualNum+mb.getFdNoinvoiceUseNum());
							dao.update("ZMCMMaterialBase.updateNoInvoiceUseNum", inMap);
						}
					}
				}
			}
		 }
		
		 return new EiInfo();
	}
	
	/**
	 * <p>更新部门的费用额度----ZMCMMaterialRation</p>
	 * <p>Function: validate</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-06-23 下午01:33:45  张坤  Create
	 * </p>
	 *
	 */
	private void updateMaterialRation(EiInfo inInfo)
	{
		
		 EiInfo outInfo = new EiInfo();
		 outInfo.addBlock(EiConstant.resultBlock);
		 outInfo.getBlock(EiConstant.resultBlock).addBlockMeta((new ZMCMTurnoverRecord()).eiMetadata);
		 Map<String, String> map = new HashMap<String, String>();
		 Double actualExportSum = new Double(0);//获取页面中实际操作的额度 
		 map.put("fdYear",  inInfo.getBlock("inqu_status").getCell(0, "fdYear").toString());
		 map.put("fdMonth", inInfo.getBlock("inqu_status").getCell(0, "fdMonth").toString());
		 map.put("orgCode", inInfo.getBlock("inqu_status").getCell(0, "fdApplicationDepartment").toString());
		 for(int i=0; i<inInfo.getBlock("result").getRowCount(); i++)
		 {	
	         Double fdApplicationExportSum = Double.valueOf(inInfo.getBlock("result").getCell(i,"fdSum").toString());
	         actualExportSum = actualExportSum + fdApplicationExportSum ;// 累加出库金额
		 }
		 map.put("fdExportRation", actualExportSum.toString());
		 outInfo.getBlock(EiConstant.resultBlock).addRow(map);
		 super.update(outInfo,"ZMCMMaterialRation.updateExportRation");  
		 
	}

	/**
	 * <p>出库列表库房名称公共选择</p>
	 * <p>Function: queryForApplication</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-8下午04:18:56 余虎
	 * </p>
	 *
	 */	
	public EiInfo queryForApplication(EiInfo inInfo) {
		EiInfo outInfo = super.query(inInfo, "ZMCMDepot.queryForExport",new ZMCMDepot());
		return outInfo;
	}
	
	/**
	 * <p>校验 单据编号 不能重复</p>
	 * <p>Function: validate</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-06-23 下午01:33:45  张坤  Create
	 * </p>
	 *
	 */
	@SuppressWarnings("rawtypes")
	private boolean validate(EiInfo inInfo, String sqlName, Map<String, String> params) {
		if(params == null) {
			params = new HashMap<String, String>();
		}
		params.put("fdNoteCode", inInfo.getBlock("inqu_status").getCellStr(0, "fdNoteCode"));

		List result = dao.query(sqlName, params);
		if(result!=null && result.size() > 0) {
			inInfo.setStatus(-1);
			inInfo.setMsg("单据编号不能重复！");
			return true;
		}
		return false;
	}
	
	
	private boolean validateBaseNum(EiInfo inInfo)
	{
		if(inInfo.getBlock("inqu_status").getCellStr(0, "fdExportType").equals("一般出库"))
		{
			for(int i=0; i<inInfo.getBlock("result").getRowCount(); i++)
			{
				String fdMaterialId = inInfo.getBlock("result").getCellStr(i, "fdMaterialId");
				String fdMaterialType = inInfo.getBlock("result").getCellStr(i, "fdMaterialType");
				String fdActualNumber = inInfo.getBlock("result").getCellStr(i, "fdActualNumber");
				
				Map inMap = new HashMap();
				inMap.put("fdMaterialId", fdMaterialId);
				List _list = dao.query("ZMCMMaterialBase.query", inMap);
				if(_list.size()>0)
				{
					ZMCMMaterialBase base = (ZMCMMaterialBase)_list.get(0);
					if(fdMaterialType.equals("有发票"))
					{
						if(Double.parseDouble(fdActualNumber)-base.getFdHasinvoiceNum() > 0)
						{
							inInfo.setStatus(-1);
							inInfo.setMsg("本次出库的数量大于库存中有发票数量，不允许出库！");
							return false;
						}
						else
						{
							inInfo.getBlock("result").setCell(i, "fdHasinvoiceNum", base.getFdHasinvoiceNum()-Double.parseDouble(fdActualNumber));
						}
					}
					else
					{
						if(Double.parseDouble(fdActualNumber)-base.getFdNoinvoiceNum() > 0)
						{
							inInfo.setStatus(-1);
							inInfo.setMsg("本次出库的数量大于库存中无发票数量，不允许出库！");
							return false;
						}
						else
						{
							inInfo.getBlock("result").setCell(i, "fdNoinvoiceNum", base.getFdNoinvoiceNum()-Double.parseDouble(fdActualNumber));
						}
					}
				}
				else
				{
					return false;
				}
			}
		}

		return true;
	}
	
	/**
	 * 
	 * <p>Function: validateDate</p>
	 * <p>Description: 验证是否在记账范围内</p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2012-3-9下午05:04:33 wangkun
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public EiInfo validateDate(EiInfo inInfo)
	{		
		String date1 = inInfo.getString("fdNoteDate");		
		if(date1 == null || "".equals(date1))//如果没有得到日期，默认为当前日期
		{
			date1 = StaticTools.getDate();
		}
		int result_int = MaterialBase.isInAccountDate(date1);
		if(result_int == -2)
		{
			inInfo.setStatus(-1);
			//StringBuffer msg = new StringBuffer("当前日期已经超出" + MaterialBase.getAccountDate(StaticTools.getDate())[2] + "月的记账范围，请在结转库存后，再办理出库！");
			StringBuffer msg = new StringBuffer("上个月没有做库存结转，请在结转库存后，再办理出库！");
			inInfo.setMsg(msg.toString());
			return inInfo;
		}
		if(result_int == 0)
		{
			inInfo.setStatus(-1);
			StringBuffer msg = new StringBuffer("该开单日期所在" + MaterialBase.getAccountDate(date1)[2] + "月的库存已经结转，无法办理出库！");
			inInfo.setMsg(msg.toString());
			return inInfo;
		}
		return inInfo;
	}
	
	
	private EiBlock generateBusinessType()
	{
		EiBlock block = new EiBlock("cmes.cm.BusinessType");
		EiColumn column = new EiColumn("value");
		column.setDescName("值");
		block.getBlockMeta().addMeta(column);
		
		Map inMap = new HashMap();
		inMap.put("value", "一般");
		block.addRow(inMap);
		
		inMap = new HashMap();
		inMap.put("value", "回收");
		block.addRow(inMap);
		
		inMap = new HashMap();
		inMap.put("value", "周转");
		block.addRow(inMap);
		
		return block;
	}
	
	private EiBlock generateMaterialType()
	{
		EiBlock block = new EiBlock("cmes.cm.MaterialType");
		EiColumn column = new EiColumn("value");
		column.setDescName("值");
		block.getBlockMeta().addMeta(column);
		
		Map inMap = new HashMap();
		inMap.put("value", "有发票");
		block.addRow(inMap);
		
		inMap = new HashMap();
		inMap.put("value", "无发票");
		block.addRow(inMap);
		
		return block;
	}
}
